import React from "react";
import { drapPositions, drapEnd, validPosition } from "./service/store";
import { hasSame } from "../example/page4/utils";

class State {
  public hovering: boolean = false
}

interface IProps {
  x: number
  y: number
}

class Square extends React.Component<IProps, State> {
  public state = new State()

  private catch: any = {}
  private ref: any

  public componentDidMount() {
    this.catch.offsetLeft = this.ref.offsetLeft
    this.catch.offsetTop = this.ref.offsetTop
    this.catch.clientHeight = this.ref.clientHeight
    this.catch.clientWidth = this.ref.clientWidth
    const currentPositions: Array<[number, number]> = [
      [this.catch.offsetLeft, this.catch.offsetTop],
      [this.catch.offsetLeft + this.catch.clientWidth, this.catch.offsetTop],
      [this.catch.offsetLeft, this.catch.offsetTop + this.catch.clientHeight],
      [this.catch.offsetLeft + this.catch.clientWidth, this.catch.offsetTop + this.catch.clientHeight],
    ]
    drapPositions.debounceTime(50).subscribe((positions) => {
      if (hasSame(positions, currentPositions)) {
        this.setState({ hovering: true })
        // positionsStore.next({key:currentPositions,value:true,name:this.props.x.toString()+this.props.y})
      } else {
        // positionsStore.next({key:currentPositions,value:false,name:this.props.x.toString()+this.props.y})
        this.setState({ hovering: false, })
      }
    })
    drapEnd.withLatestFrom(drapPositions).subscribe(([_, positions]) => {
      if (hasSame(positions, currentPositions)) {
        // console.log(positions)
        validPosition.next(currentPositions)
      }
    })
  }

  public render() {
    const fill = (this.props.x + this.props.y) % 2 ? 'black' : 'white';
    const stroke = this.state.hovering ? 'red' : 'yellow';


    return <div ref={(ref) => this.ref = ref} style={{
      backgroundColor: fill,
      color: stroke,
      width: '10%',
      height: '10%',
      display: 'inline-block'
    }}>
      {this.props.x},{this.props.y}
    </div>
  }
}

export default class Grid extends React.Component {
  public render() {
    const squires = []
    for (let i = 0; i < 10; i += 1) {
      for (let j = 0; j < 10; j += 1) {
        squires.push(<Square x={i} y={j} />)
      }
    }
    return squires
  }
}